package com.bst.etl.service.impl;

import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.bst.common.constant.JobConstant;
import com.bst.common.exception.base.BaseException;
import com.bst.common.utils.self.LoginAPIUtils;
import com.bst.common.vo.DataExecParamVO;
import com.bst.common.vo.TableDDLColumnVO;
import com.bst.etl.service.IEtlBaseVariService;
import com.bst.etl.service.ITableDDLService;
import com.bst.system.framework.datasource.DynamicDataSource;
import com.bst.system.framework.utils.DBUtil;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bst.etl.mapper.EtlDrawBaseMapper;
import com.bst.etl.domain.EtlDrawBase;
import com.bst.etl.service.IEtlDrawBaseService;
import com.bst.common.core.text.Convert;
import org.springframework.util.StringUtils;

/**
 * 基础抽取Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-06-20
 */
@Service("etlDrawBaseService")
public class EtlDrawBaseServiceImpl implements IEtlDrawBaseService 
{
    @Autowired
    private EtlDrawBaseMapper etlDrawBaseMapper;
    @Autowired
    private ITableDDLService tableDDLService;

    /**
     * 查询基础抽取
     * 
     * @param idDrawBase 基础抽取主键
     * @return 基础抽取
     */
    @Override
    public EtlDrawBase selectEtlDrawBaseByIdDrawBase(Long idDrawBase)
    {
        return etlDrawBaseMapper.selectEtlDrawBaseByIdDrawBase(idDrawBase);
    }

    /**
     * 查询基础抽取列表
     * 
     * @param etlDrawBase 基础抽取
     * @return 基础抽取
     */
    @Override
    public List<EtlDrawBase> selectEtlDrawBaseList(EtlDrawBase etlDrawBase)
    {
        return etlDrawBaseMapper.selectEtlDrawBaseList(etlDrawBase);
    }

    /**
     * 新增基础抽取
     * 
     * @param etlDrawBase 基础抽取
     * @return 结果
     */
    @Override
    public int insertEtlDrawBase(EtlDrawBase etlDrawBase)
    {
        etlDrawBase.setFgTbCre(1);
        etlDrawBase.setDtSysCre(new Date());
        etlDrawBase.setNaEmpCre(LoginAPIUtils.getLoginUsename());
        return etlDrawBaseMapper.insertEtlDrawBase(etlDrawBase);
    }

    /**
     * 修改基础抽取
     * 
     * @param etlDrawBase 基础抽取
     * @return 结果
     */
    @Override
    public int updateEtlDrawBase(EtlDrawBase etlDrawBase)
    {
        etlDrawBase.setDtSysModi(new Date());
        etlDrawBase.setNaEmpModi(LoginAPIUtils.getLoginUsename());
        return etlDrawBaseMapper.updateEtlDrawBase(etlDrawBase);
    }

    /**
     * 批量删除基础抽取
     * 
     * @param idDrawBases 需要删除的基础抽取主键
     * @return 结果
     */
    @Override
    public int deleteEtlDrawBaseByIdDrawBases(String idDrawBases)
    {
        return etlDrawBaseMapper.deleteEtlDrawBaseByIdDrawBases(Convert.toStrArray(idDrawBases));
    }

    /**
     * 删除基础抽取信息
     * 
     * @param idDrawBase 基础抽取主键
     * @return 结果
     */
    @Override
    public int deleteEtlDrawBaseByIdDrawBase(Long idDrawBase)
    {
        return etlDrawBaseMapper.deleteEtlDrawBaseByIdDrawBase(idDrawBase);
    }

    @Override
    public List<DataExecParamVO> findBaseTaskByIds(List<String> ids, Date startDate, Date endDate) {
        List<DataExecParamVO> paramVOList = new ArrayList<>();
        EtlDrawBase base;
        List<EtlDrawBase> taskOdsList =new ArrayList<>();
        EtlDrawBase etlTaskOds;DataExecParamVO paramVO;
        for(String id:ids) {
            base = this.selectEtlDrawBaseByIdDrawBase(Long.parseLong(id));
            paramVO = new DataExecParamVO();
            paramVO.setDelSql(base.getSqlBefore());
            paramVO.setQuerySql(base.getSqlQry());
            if("ods_inter".equals(base.getSdDrawcls())) {
                paramVO.setJobType(JobConstant.JOB_TYPE_BASE_INTER);
            } else {
                paramVO.setJobType(JobConstant.JOB_TYPE_BASE);
            }
            paramVO.setStartDate(startDate);
            paramVO.setEndDate(endDate);
            paramVO.setDes(base.getNa()+"["+base.getCdTbTar()+"]");
            paramVO.setTbTar(base.getCdTbTar());
            paramVO.setIdDbSou(base.getIdDb()+"");
            paramVO.setIdDbTar(JobConstant.DB_CLS_DW);
            paramVO.setUrl(base.getUrl());
            paramVO.setEuReq(base.getEuReq());
            paramVO.setInter(base.getInter());
            paramVOList.add(paramVO);
        }
        return paramVOList;
    }

    @Override
    public List<TableDDLColumnVO> createOrModiTableColumnList(Long idTaskOds) throws BaseException {
        EtlDrawBase etlTaskOds = etlDrawBaseMapper.selectEtlDrawBaseByIdDrawBase(idTaskOds);
        if (etlTaskOds == null) throw new BaseException(String.format("ODS配置记录未找到,idTaskOds:[%s]", idTaskOds));

        String odsQuerySql = etlTaskOds.getSqlQry();
        String tbTar = etlTaskOds.getCdTbTar();
        List<TableDDLColumnVO> createTableDDLVO = tableDDLService.generateTableDDLColumnList(this.sqlVariHandler(odsQuerySql,null), etlTaskOds.getIdDb().toString(), tbTar, JobConstant.DB_CLS_DW);
        return createTableDDLVO;
    }

    @Autowired
    IEtlBaseVariService etlBaseVariService;
    /**
     * sql变量替换
     * @return
     */
    private String sqlVariHandler(String sql,Long jobId) {
        Map<String,String> vari=etlBaseVariService.queryAllVariByIdJob(jobId);
        String delSql,qrySql;
        for(Map.Entry<String,String> entry:vari.entrySet()) {
            sql = sql.replaceAll("\\$\\{"+entry.getKey()+"\\}",entry.getValue());
        }
        return sql;
    }

    @Override
    public void execTableDDLColumns(Long id) throws BaseException {
        EtlDrawBase etlTaskOds = etlDrawBaseMapper.selectEtlDrawBaseByIdDrawBase(id);
        if (etlTaskOds == null)
            throw new BaseException(String.format("ODS配置记录未找到,idTaskOds:[%s]",id));
        if (StringUtils.isEmpty(etlTaskOds.getCdTbTar()))
            throw new BaseException(String.format("ODS配置记录目标表未找到,idTaskOds:[%s][%s]", id, etlTaskOds.getCdTbTar()));
        List<TableDDLColumnVO> columnList = this.createOrModiTableColumnList(id);
        tableDDLService.execTableDDLColumnListOfDW(columnList, etlTaskOds.getCdTbTar().toUpperCase());
        this.updateEtlDrawBase(etlTaskOds);
    }

    @Override
    public List<String> findDateFld(Long idDrawBase) {
        EtlDrawBase etlDrawBase = this.selectEtlDrawBaseByIdDrawBase(idDrawBase);
        Triple<List<String>, List<Integer>, List<String>> columnMetaDataTo =
                DBUtil.getColumnMetaDataTo(DynamicDataSource.getDataSourceById(JobConstant.DB_CLS_DW), etlDrawBase.getCdTbTar());
        //获取时间格式字段
        if(columnMetaDataTo==null) return null;
        List<String> dateFid = new ArrayList<>();
        List<Integer> colTypes = columnMetaDataTo.getMiddle();
        List<String> left = columnMetaDataTo.getLeft();
        for (int i = 0; i < colTypes.size(); i++) {
            Integer colType = colTypes.get(i);
            if (colType == Types.DATE || colType == Types.TIMESTAMP || colType == Types.TIME) {
                dateFid.add(left.get(i).toUpperCase());
            }
        }
        return dateFid;
    }

    @Override
    public List<EtlDrawBase> selectNotInJobList(Integer idJob) {
        return etlDrawBaseMapper.selectNotInJobList(idJob);
    }

    @Override
    public List<EtlDrawBase> selectByJobId(Integer idJob) {
        return etlDrawBaseMapper.selectByJobId(idJob);
    }
}
